class Snake{
    //获取蛇头元素
    head:HTMLElement;
    //蛇的身体（包括蛇头）
    bodies:HTMLCollection;
    //获取蛇的容器
    element:HTMLElement

    constructor(){
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = document.getElementById('snake')!.getElementsByTagName('div');
        this.element = document.getElementById('snake')!;
    }

    //获取蛇头坐标
    get X(){
        return this.head.offsetLeft
    }

    get Y(){
        return this.head.offsetTop
    }

    //设置坐标
    set X(value){
        //如果新旧值相同则直接返回不做修改
        if(this.X === value){
            return;
        }
        //X的合法范围0-290
        if(value < 0 || value >290){
            //蛇撞墙了
            throw new Error('蛇撞墙了')
        }
        //修改x时蛇向右移动不能向左掉头
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value){
            if(value > this.X){
                value = this.X - 10;
            }else{
                value = this.X + 10;
            }
        }

        this.moveBody()
        this.head.style.left =value + 'px'
        this.checkHeadBody();
        
    }
    set Y(value){
        if(this.Y === value){
            return;
        }
        if(value<0 || value >290){
            //蛇撞墙了
            throw new Error('GAME OVER')
        }
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value){
            if(value > this.Y){
                value = this.Y - 10;
            }else{
                value = this.Y + 10;
            }
        }
        this.moveBody()
        this.head.style.top = value + 'px'
        this.checkHeadBody();
        
    }

    //蛇增加身体的方法
    addBody(){
        //给element中添加div
        this.element.insertAdjacentHTML("beforeend","<div></div>")
    }

    //蛇身体移动的方法（难点）
    moveBody(){
        //将后边的身体4设置为前面身体3的位置 以此类推
        //遍历获取所有身体
        for(let i = this.bodies.length -1; i>0;i--){
            //获取前边身体的位置
            let X = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i-1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = X + 'px';
            (this.bodies[i] as HTMLElement).style.top = Y + 'px';
        }
    }

    //检查蛇头是否与身体相撞
    checkHeadBody(){
        //获取身体坐标
        for(let i = 1; i < this.bodies.length; i ++){
            let bd = this.bodies[i] as HTMLElement;
            if(this.X === bd.offsetLeft && this.Y ===bd.offsetTop){
                throw new Error('GAME OVER')
            }
        }
    }
}

export default Snake